<template>
  <div id="app">
    <!-- 顶部导航栏 -->
    <div class="app-header">
      <h1>充电地图</h1>
      <div class="header-actions">
        <button class="location-btn" @click="handleLocation">
          <span class="location-icon">📍</span>
          定位
        </button>
      </div>
    </div>

    <!-- 地图区域 -->
    <div class="main-content">
      <div class="map-section">
        <AMapContainer ref="mapRef" @startCharge="handleMapStartCharge" />
        
        <!-- 选中的充电站详情 -->
        <div v-if="selectedStation" class="station-detail-panel">
          <div class="detail-header">
            <h3>{{ selectedStation.stationName }}</h3>
            <button class="close-btn" @click="selectedStation = null">×</button>
          </div>
          <div class="detail-content">
            <div class="detail-row">
              <span class="label">地址:</span>
              <span class="value">{{ selectedStation.address }}</span>
            </div>
            <div class="detail-row">
              <span class="label">距离:</span>
              <span class="value distance">{{ selectedStation.distance || '计算中...' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">状态:</span>
              <span class="value status-tag" :class="getStatusClass(selectedStation.status)">
                {{ getStatusText(selectedStation.status) }}
              </span>
            </div>
            <div class="detail-row">
              <span class="label">空闲桩位:</span>
              <span class="value available-count">{{ selectedStation.quickAvailableNum + selectedStation.slowAvailableNum }}/{{ selectedStation.quickChargeNum + selectedStation.slowChargeNum }}</span>
            </div>
            <div class="detail-row">
              <span class="label">快充:</span>
              <span class="value">{{ selectedStation.quickAvailableNum }}/{{ selectedStation.quickChargeNum }}</span>
            </div>
            <div class="detail-row">
              <span class="label">慢充:</span>
              <span class="value">{{ selectedStation.slowAvailableNum }}/{{ selectedStation.slowChargeNum }}</span>
            </div>
            <div class="detail-row">
              <span class="label">价格:</span>
              <span class="value price">¥{{ selectedStation.totalCostPrice }}/度</span>
            </div>
            <div class="detail-actions">
              <button class="nav-btn" @click="startNavigation">导航前往</button>
              <button class="charge-btn" :disabled="(selectedStation.quickAvailableNum + selectedStation.slowAvailableNum) === 0 || store.getStationStatus(selectedStation) === 'maintenance'" @click="startCharging">
                {{ (selectedStation.quickAvailableNum + selectedStation.slowAvailableNum) === 0 ? '无空闲桩位' : store.getStationStatus(selectedStation) === 'maintenance' ? '维护中' : '开始充电' }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 充电站列表 -->
      <div class="station-list">
        <div class="list-header">
          <h3>附近充电站</h3>
          <span class="count">{{ store.stations.length }}个站点</span>
        </div>
        
        <div class="stations">
          <div 
            v-for="station in store.stations" 
            :key="station.stationId"
            class="station-item"
            :class="{ 'selected': selectedStation?.stationId === station.stationId }"
            @click="selectStation(station)"
          >
            <div class="station-info">
              <div class="name">{{ station.stationName }}</div>
              <div class="address">{{ station.address }}</div>
              <div class="details">
                <span class="status-tag" :class="getStatusClass(store.getStationStatus(station))">
                  {{ getStatusText(store.getStationStatus(station)) }}
                </span>
                <span class="price">¥{{ station.totalCostPrice }}/度</span>
                <span class="distance" v-if="station.distance">{{ store.formatDistance(station.distance) }}</span>
              </div>
            </div>
            <div class="station-availability">
              <div class="available">{{ store.getAvailableCount(station) }}/{{ store.getTotalCount(station) }}</div>
              <div class="available-text">空闲</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- StationDetail组件使用 -->
    <StationDetail 
      v-if="selectedStation && showDetailPanel"
      :station="selectedStation"
      @close="showDetailPanel = false"
      @navigate="startNavigation"
      @startCharge="handleStationDetailStartCharge"
    />
    
    <!-- 充电模拟面板 -->
    <div v-if="isCharging" class="charging-panel">
      <div class="charging-header">
        <h3>🔋 正在充电</h3>
        <span class="station-name">{{ selectedStation?.stationName }}</span>
      </div>
      
      <!-- 进度条 -->
      <div class="progress-container">
        <div class="progress-bar">
          <div class="progress-fill" :style="{width: chargingProgress + '%'}"></div>
        </div>
        <div class="progress-text">{{ Math.round(chargingProgress) }}%</div>
      </div>
      
      <div class="charging-info">
        <div class="info-item">
          <span class="info-label">已充电量:</span>
          <span class="info-value">{{ chargedPower.toFixed(2) }} kWh</span>
        </div>
        <div class="info-item">
          <span class="info-label">充电时间:</span>
          <span class="info-value">{{ formatChargingTime(chargingTime) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">预计费用:</span>
          <span class="info-value price">¥{{ (chargedPower * (selectedStation?.totalCostPrice || 0)).toFixed(2) }}</span>
        </div>
      </div>
      
      <button class="stop-btn" @click="stopCharging">
        <span class="btn-icon">⏹️</span> 停止充电
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStationsStore } from '@/stores/station'
import AMapContainer from '@/components/Map/AMapContainer.vue'
import StationDetail from '@/components/StationDetail/StationDetail.vue'

const store = useStationsStore()
const mapRef = ref<InstanceType<typeof AMapContainer>>()

// 响应式数据
const selectedStation = ref<any>(null)
const showDetailPanel = ref(false)

// 充电状态
const isCharging = ref(false)
const chargingProgress = ref(0)
const chargedPower = ref(0)
const chargingTime = ref(0)
let chargingInterval: any = null

// 组件挂载
onMounted(() => {
  store.loadStations()
})

// 选择充电站
const selectStation = (station: any) => {
  selectedStation.value = station
  store.setSelectedStation(station)
  // 显示详细的StationDetail面板
  showDetailPanel.value = true
}

// 获取状态对应的CSS类
const getStatusClass = (status: string) => {
  const classes: any = {
    free: 'status-free',
    busy: 'status-busy', 
    maintenance: 'status-maintenance'
  }
  return classes[status] || 'status-free'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: any = {
    free: '空闲',
    busy: '繁忙',
    maintenance: '维护'
  }
  return texts[status] || '未知'
}

// 处理定位
const handleLocation = () => {
  if (mapRef.value) {
    // 暂时注释掉，等待mapRef正确初始化
    // mapRef.value?.locateUser?.()
  }
}

// 开始导航
const startNavigation = () => {
  if (selectedStation.value && mapRef.value) {
    // 暂时注释掉，等待mapRef正确初始化
    // mapRef.value?.startNavigation?.(selectedStation.value)
  }
}

// 格式化充电时间
const formatChargingTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}分${secs}秒`
}

// 开始充电
const startCharging = () => {
  if (!selectedStation.value) {
    alert('请先选择一个充电站')
    return
  }
  
  const availableCount = store.getAvailableCount(selectedStation.value)
  const stationStatus = store.getStationStatus(selectedStation.value)
  
  if (availableCount <= 0) {
    alert('当前充电站没有可用的充电桩，请选择其他充电站')
    return
  }
  
  if (stationStatus === 'maintenance') {
    alert('当前充电站处于维护状态，暂时无法使用')
    return
  }
  
  // 显示开始充电确认对话框
  const confirmStart = window.confirm(`确认在「${selectedStation.value.stationName}」开始充电？\n快充: ${selectedStation.value.quickAvailableNum}/${selectedStation.value.quickChargeNum} 可用\n慢充: ${selectedStation.value.slowAvailableNum}/${selectedStation.value.slowChargeNum} 可用\n单价: ¥${selectedStation.value.totalCostPrice}/度`)
  
  if (!confirmStart) return
  
  // 开始充电
  isCharging.value = true
  chargingProgress.value = 0
  chargedPower.value = 0
  chargingTime.value = 0
  
  // 根据是否有快充口选择充电功率
  const chargePower = selectedStation.value.quickAvailableNum > 0 ? 60 : 7 // 快充60kW，慢充7kW
  
  console.log(`🔌 开始充电 - 充电站: ${selectedStation.value.stationName}, 功率: ${chargePower}kW`)
  
  // 每秒更新一次充电状态
  chargingInterval = setInterval(() => {
    if (chargingProgress.value < 100) {
      chargingProgress.value += 2
      // 根据功率计算充电量 (kWh = kW * h)
      chargedPower.value += (chargePower * 0.033) // 0.033小时 = 2分钟
      chargingTime.value += 1
      
      // 随机模拟可能的充电中断情况（可选功能）
      if (Math.random() < 0.005) { // 0.5%的概率出现充电中断
        handleChargingError('充电过程出现短暂中断，正在恢复...')
      }
    } else {
      stopCharging()
    }
  }, 1000)
}

// 处理充电异常
const handleChargingError = (message: string) => {
  console.warn(`⚠️ ${message}`)
  // 这里可以添加错误处理逻辑
}

// 停止充电
const stopCharging = () => {
  isCharging.value = false
  if (chargingInterval) {
    clearInterval(chargingInterval)
    chargingInterval = null
    
    console.log('🔋 充电已停止')
    
    // 显示支付界面
    if (selectedStation.value) {
      showPayment(selectedStation.value, chargedPower.value)
    }
  }
}

// 处理StationDetail组件的开始充电事件
const handleStationDetailStartCharge = (station: any) => {
  selectedStation.value = station
  startCharging()
}

// 处理地图组件的开始充电事件
const handleMapStartCharge = (station: any) => {
  selectedStation.value = station
  startCharging()
}

// 显示支付界面
const showPayment = (station: any, power: number) => {
  if (power <= 0) {
    alert('充电量为0，无需支付')
    return
  }
  
  const totalAmount = (power * station.totalCostPrice).toFixed(2)
  const duration = formatChargingTime(chargingTime.value)
  
  // 创建更友好的支付确认HTML
  const paymentDiv = document.createElement('div')
  paymentDiv.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  `
  
  paymentDiv.innerHTML = `
    <div style="
      background: white;
      border-radius: 12px;
      padding: 24px;
      width: 90%;
      max-width: 400px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    ">
      <h3 style="margin-top:0; color:#1890ff; text-align:center;">充电完成</h3>
      <div style="margin: 20px 0;">
        <div style="display:flex; justify-content:space-between; margin-bottom:12px; padding-bottom:12px; border-bottom:1px solid #f0f0f0;">
          <span style="color:#666;">充电站:</span>
          <span style="font-weight:500; text-align:right;">${station.stationName}</span>
        </div>
        <div style="display:flex; justify-content:space-between; margin-bottom:12px; padding-bottom:12px; border-bottom:1px solid #f0f0f0;">
          <span style="color:#666;">充电时长:</span>
          <span style="font-weight:500;">${duration}</span>
        </div>
        <div style="display:flex; justify-content:space-between; margin-bottom:12px; padding-bottom:12px; border-bottom:1px solid #f0f0f0;">
          <span style="color:#666;">已充电量:</span>
          <span style="font-weight:500;">${power.toFixed(2)} kWh</span>
        </div>
        <div style="display:flex; justify-content:space-between; margin-bottom:12px; padding-bottom:12px; border-bottom:1px solid #f0f0f0;">
          <span style="color:#666;">单价:</span>
          <span style="font-weight:500;">¥${station.totalCostPrice}/度</span>
        </div>
        <div style="display:flex; justify-content:space-between; margin-bottom:24px;">
          <span style="font-weight:bold;">应付金额:</span>
          <span style="font-weight:bold; color:#ff4d4f; font-size:18px;">¥${totalAmount}</span>
        </div>
      </div>
      <div style="display:flex; gap:12px;">
        <button id="pay-cancel" style="
          flex:1;
          padding:10px;
          border:1px solid #d9d9d9;
          background:white;
          border-radius:6px;
          cursor:pointer;
          font-size:16px;
        ">取消</button>
        <button id="pay-confirm" style="
          flex:1;
          padding:10px;
          background:#1890ff;
          color:white;
          border:none;
          border-radius:6px;
          cursor:pointer;
          font-size:16px;
        ">确认支付</button>
      </div>
    </div>
  `
  
  document.body.appendChild(paymentDiv)
  
  // 绑定取消按钮事件
  const cancelBtn = document.getElementById('pay-cancel')
  if (cancelBtn) {
    cancelBtn.onclick = () => {
      document.body.removeChild(paymentDiv)
    }
  }
  
  // 绑定确认支付按钮事件
  const confirmBtn = document.getElementById('pay-confirm')
  if (confirmBtn) {
    confirmBtn.onclick = () => {
      // 模拟支付成功
      setTimeout(() => {
        document.body.removeChild(paymentDiv)
        
        // 显示支付成功提示
        const successDiv = document.createElement('div')
        successDiv.style.cssText = `
          position: fixed;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          background: rgba(82, 196, 26, 0.9);
          color: white;
          padding: 20px 30px;
          border-radius: 8px;
          z-index: 9999;
          font-size: 16px;
          text-align: center;
        `
        successDiv.innerHTML = `
          <div style="font-size:32px; margin-bottom:10px;">✅</div>
          <div>支付成功！</div>
          <div style="margin-top:8px; font-size:14px;">感谢您使用我们的充电服务</div>
        `
        document.body.appendChild(successDiv)
        
        // 3秒后自动关闭成功提示
        setTimeout(() => {
          document.body.removeChild(successDiv)
        }, 3000)
        
        console.log(`💳 支付成功 - 金额: ¥${totalAmount}`)
      }, 1000)
    }
  }
}
</script>

<style>
/* 重置样式确保全屏显示 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  z-index: 1000;
  flex-shrink: 0;
}

.app-header h1 {
  margin: 0;
  font-size: 18px;
  color: #1890ff;
}

.location-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.location-btn:hover {
  background: #40a9ff;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 地图区域 */
.map-section {
  flex: 1;
  position: relative;
  padding: 10px;
  background: #f0f2f5;
  min-height: 0;
}

/* 充电站列表 */
.station-list {
  height: 220px;
  background: white;
  border-top: 1px solid #e8e8e8;
  overflow-y: auto;
  flex-shrink: 0;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
  background: #fafafa;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
}

.count {
  color: #666;
  font-size: 14px;
}

.stations {
  padding: 8px;
}

.station-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  transition: all 0.3s;
}

.station-item:hover {
  background: #f5f5f5;
}

.station-item.selected {
  border-color: #1890ff;
  background: #f0f8ff;
}

.station-info {
  flex: 1;
}

.name {
  font-weight: 600;
  margin-bottom: 4px;
}

.address {
  color: #666;
  font-size: 12px;
  margin-bottom: 6px;
}

.details {
  display: flex;
  gap: 6px;
  font-size: 11px;
  flex-wrap: wrap;
  align-items: center;
}

.status-tag {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
}

.status-free {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-busy {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.status-maintenance {
  background: #fff2f0;
  color: #f5222d;
  border: 1px solid #ffccc7;
}

.power, .price {
  color: #666;
}

.distance {
  color: #1890ff;
  background: #f0f8ff;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}

.station-availability {
  text-align: center;
  padding: 8px;
  min-width: 60px;
}

.available {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
}

.available-text {
  font-size: 12px;
  color: #666;
}

/* 充电站详情面板 */
.station-detail-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  z-index: 999;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.detail-header h3 {
  margin: 0;
  font-size: 16px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}

.detail-content {
  padding: 16px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  font-weight: 500;
}

.distance {
  color: #1890ff;
  font-weight: 600;
}

.available-count {
  color: #52c41a;
  font-weight: 600;
}

.price {
  color: #fa8c16;
  font-weight: 600;
}

.detail-actions {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}

.nav-btn, .charge-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.nav-btn {
  background: #1890ff;
  color: white;
}

.nav-btn:hover {
  background: #40a9ff;
}

.charge-btn {
  background: #52c41a;
  color: white;
}

.charge-btn:hover:not(:disabled) {
  background: #73d13d;
}

.charge-btn:disabled {
  background: #d9d9d9;
  color: #999;
  cursor: not-allowed;
}

/* 充电面板 */
.charging-panel {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 320px;
  background: linear-gradient(135deg, #f6ffed, #e6f7ff);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  z-index: 1001;
  padding: 20px;
  border: 1px solid #b7eb8f;
}

.charging-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  text-align: center;
  padding-bottom: 0;
  border-bottom: none;
}

.charging-header h3 {
  margin: 0 0 5px 0;
  color: #1890ff;
  font-size: 20px;
}

.charging-header .station-name {
  color: #666;
  font-size: 14px;
}

/* 进度条样式 */
.progress-container {
  margin-bottom: 20px;
}

.progress-bar {
  width: 100%;
  height: 12px;
  background: #f0f0f0;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 8px;
  box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #52c41a, #73d13d);
  border-radius: 6px;
  transition: width 0.3s ease;
  box-shadow: 0 0 6px rgba(82, 196, 26, 0.5);
}

.progress-text {
  text-align: center;
  font-weight: bold;
  color: #52c41a;
  font-size: 16px;
}

.charging-info {
  margin-bottom: 20px;
  padding: 0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #666;
  font-size: 14px;
}

.info-value {
  font-weight: 500;
  font-size: 14px;
}

.info-value.price {
  color: #ff4d4f;
  font-weight: bold;
}

.stop-btn {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
  color: white;
  border: none;
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  width: 100%;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.stop-btn:hover {
  background: linear-gradient(135deg, #ff7875, #ffccc7);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
}

.stop-btn:active {
  transform: translateY(0);
}
</style>